package com.bridge.console.web;

import com.bridge.console.model.enums.AccountRoleEnum;
import com.bridge.console.service.account.ContextHolder;
import com.bridge.console.service.account.SessionContext;
import com.bridge.console.utils.EnumUtil;
import com.bridge.console.utils.ex.BusinessCheckFailException;
import com.bridge.console.utils.result.BaseErrorEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Jay
 * @version v1.0
 * @description 基类封装登录人角色相关信息
 * @date 2019-01-24 17:12
 */
@Component
public class BaseController {


    @Autowired
    private ContextHolder contextHolder;


    /**
     * 是否为管理员
     *
     * @return
     */
    public boolean isAdmin() {
        return judgeAccountRole(1);
    }


    /**
     * 是否为普通用户
     *
     * @return
     */
    public boolean isUser() {
        return judgeAccountRole(2);
    }

    /**
     * 是否为团队leader
     *
     * @return
     */
    public boolean isTeamLeader() {
        return judgeAccountRole(3);
    }

    /**
     * 获取登录人身份
     *
     * @return
     */
    public SessionContext getSessionContext() {
        SessionContext sessionContext = contextHolder.getSessionContext();
        if (sessionContext == null) {
            throw new BusinessCheckFailException(BaseErrorEnum.BNS_CHK_ERROR.getCode(), "sessionContext为空");
        }
        return sessionContext;
    }


    //-----------------------------------------------private method----------------------------------------------------

    /**
     * 当前登录角色是否为admin
     *
     * @return
     */
    private boolean judgeAccountRole(Integer tag) {
        Integer accountRole = getSessionContext().getAccountRole();
        if (!EnumUtil.getKeys(AccountRoleEnum.class).contains(accountRole)) {
            throw new BusinessCheckFailException(BaseErrorEnum.BNS_CHK_ERROR.getCode(), "角色非法");
        }
        if (tag == 1) {
            return accountRole == AccountRoleEnum.ROLE_ADMIN.getKey();
        }
        if (tag == 2) {
            return accountRole == AccountRoleEnum.ROLE_USER.getKey();
        }
        if (tag == 3) {
            return accountRole == AccountRoleEnum.ROLE_TEAM_LEADER.getKey();
        }
        throw new BusinessCheckFailException(BaseErrorEnum.BNS_CHK_ERROR.getCode(), "参数异常");
    }

}
